package cn.gene.timeyan.chat.config;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.Objects;

/**
 * 拦截器*
 *
 * @author LWG
 * @date 2022/8/14 19:16
 * @since 1.0.0 @gene.cn
 */
public class WebSocketHandlerInterceptor extends HttpSessionHandshakeInterceptor {

    /**
     * @param request
     * @param response
     * @param wsHandler
     * @param attributes
     * @return boolean
     * @Description: 握手之前
     * @Author Mr.Fang
     * @date 2021/11/14 13:18
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpServletRequest re = servletRequest.getServletRequest();
        Object token = re.getParameter("token");
        Object admin = re.getParameter("admin");
        if (Objects.isNull(token)) {
            return false;
        }
        re.getSession().setAttribute("admin", admin);
        re.getSession().setAttribute("token", token);
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    /**
     * @param request
     * @param response
     * @param wsHandler
     * @param ex
     * @return boolean
     * @Description: 握手之后
     * @Author Mr.Fang
     * @date 2021/11/14 13:18
     */
    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
